package com.cc.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.pms.service.ITeamApplicationService;
import com.cc.pms.service.ITeamService;
import com.cc.common.core.domain.R;
import com.cc.common.utils.DateUtils;
import com.cc.common.utils.SecurityUtils;
import com.cc.pms.domain.TeamMember;
import com.cc.pms.domain.vo.TeamMemberVo;
import com.cc.pms.mapper.TeamMemberMapper;
import com.cc.pms.service.ITeamMemberService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 队伍成员表 服务实现类
 * </p>
 *
 * @author corleone
 * @since 2025-04-19
 */
@Service
public class TeamMemberServiceImpl extends ServiceImpl<TeamMemberMapper, TeamMember> implements ITeamMemberService {

    @Resource
    private ITeamService iTeamService;

    @Resource
    private ITeamApplicationService iTeamApplicationService;

    @Override
    public List<TeamMemberVo> queryTeamMemberVo(Long teamId) {
        return baseMapper.queryTeamMemberVo(teamId);
    }

    @Override
    public void removeByTeamId(Long teamId) {
        lambdaUpdate().eq(TeamMember::getTeamId, teamId).remove();
    }

    @Override
    public R<Boolean> removeMembers(Long teamId, Long[] memberIds) {
        if (memberIds == null || memberIds.length == 0) {
            return R.fail(-1, "请求数据为空");
        }
        removeMembersByTeamId(teamId, memberIds);
        List<TeamMember> teamMembers = queryMemberByTeamId(teamId);
        if (teamMembers.isEmpty()) {
            iTeamService.removeByTeamId(teamId);
        } else {
            long currentMembers = teamMembers.stream().filter(member -> member.getIsCaptain() == 1).count();
            if (currentMembers == 0) {
                TeamMember teamMember = teamMembers.get(0);
                teamMember.setIsCaptain(1);
                updateById(teamMember);
            }
            iTeamService.updateTeamMembersCount(teamId, (int) currentMembers);
        }
        // 对应的用户申请也要被清除
        iTeamApplicationService.removeMemberApplication(teamId, Arrays.stream(memberIds).collect(Collectors.toList()));
        return R.ok();
    }

    @Override
    public void setCaptain(TeamMember teamMember) {
        lambdaUpdate().eq(TeamMember::getTeamId, teamMember.getTeamId()).set(TeamMember::getIsCaptain, 0).update();
        lambdaUpdate().eq(TeamMember::getTeamId, teamMember.getTeamId()).eq(TeamMember::getUserId, teamMember.getUserId()).set(TeamMember::getIsCaptain, 1).update();
    }

    @Override
    public R<Boolean> exitTeam(Long teamId) {
        return forcingMemberExitTeam(teamId, SecurityUtils.getUserId());
    }

    private TeamMember queryTeamMemberByUserIdAndTeamId(Long userId, Long teamId) {
        return lambdaQuery().eq(TeamMember::getUserId, userId).eq(TeamMember::getTeamId, teamId).last(" limit 1").one();
    }

    @Override
    public R<Boolean> forcingMemberExitTeam(Long teamId, Long userId) {
        TeamMember member = queryTeamMemberByUserIdAndTeamId(userId, teamId);
        if (member == null) {
            return R.fail(-1, "队员信息不存在");
        }
        return removeMembers(teamId, new Long[]{userId});
    }

    @Override
    public void addMember(TeamMember member) {
        save(member);
        List<TeamMember> teamMembers = queryMemberByTeamId(member.getTeamId());
        iTeamService.updateTeamMembersCount(member.getTeamId(), teamMembers.size());
    }

    @Override
    public R<Long> joinTeam(Long teamId) {
        TeamMember member = new TeamMember();
        member.setJoinTime(DateUtils.getTime());
        member.setUserId(SecurityUtils.getUserId());
        member.setTeamId(teamId);
        return save(member) ? R.ok(member.getId()) : R.fail(-1, "加入队伍失败");
    }

    @Override
    public R<Long> joinTeam(TeamMember member) {
        TeamMember teamMember = queryTeamMemberByUserIdAndTeamId(member.getUserId(), member.getTeamId());
        if (teamMember != null) {
            return R.fail(-1, "用户已存在队伍中,不可再次加入");
        }
        addMember(member);
        return R.ok(member.getId());
    }

    @Override
    public int queryManageTeamCount(Long userId) {
        LambdaQueryWrapper<TeamMember> lqw = Wrappers.lambdaQuery();
        lqw.eq(TeamMember::getUserId, userId);
        lqw.eq(TeamMember::getIsCaptain, 1);
        return (int) count(lqw);
    }

    private void removeMembersByTeamId(Long teamId, Long[] memberIds) {
        lambdaUpdate().eq(TeamMember::getTeamId, teamId).in(TeamMember::getUserId, Arrays.stream(memberIds).toArray()).remove();
    }

    private List<TeamMember> queryMemberByTeamId(Long teamId) {
        return lambdaQuery().eq(TeamMember::getTeamId, teamId).list();
    }


}
